<template>
  <div>
    <el-card class="el-card">
      <!--条件搜索-->
      <el-form ref="postQueryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="岗位名称" prop="postName">
          <el-input
            placeholder="请输入岗位名称"
            clearable
            size="default"
            v-model="queryParams.postName"
          />
        </el-form-item>
        <el-form-item label="岗位编码" prop="postCode">
          <el-input
            placeholder="请输入岗位编码"
            clearable
            size="default"
            v-model="queryParams.postCode"
          />
        </el-form-item>
        <el-form-item label="岗位状态" prop="postStatus">
          <el-select
            aria-placeholder="请选择岗位状态"
            size="default"
            v-model="queryParams.postStatus"
          >
            <el-option
              v-for="item in postStatusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="beginTime">
          <el-date-picker
            size="default"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            v-model="queryParams.beginTime"
            placeholder="请选择开始时间"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            size="default"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            v-model="queryParams.endTime"
            placeholder="请选择结束时间"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="postQuerySearch">
            <template #icon>
              <i-ep-search />
            </template>
            查询
          </el-button>
          <el-button @click="postResetQueryForm">
            <template #icon>
              <i-ep-refresh />
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
      <!--操作按钮-->
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button
            v-if="hasPermission('api.sysPost.store')"
            plain
            type="primary"
            @click="handCreatePost"
          >
            <template #icon>
              <i-ep-plus />
            </template>
            新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-if="hasPermission('api.sysPost.batch.destroy')"
            plain
            type="danger"
            :disabled="multiple"
            @click="handBacthDeletePost"
          >
            <template #icon>
              <i-ep-delete />
            </template>
            批量删除
          </el-button>
        </el-col>
      </el-row>
      <!--列表-->
      <el-table
        border
        stripe
        class="w-full"
        header-cell-class-name="text-[#606266] !bg-[#eef1f6]"
        v-loading="tableData.loading"
        :data="tableData.data"
        @selection-change="handSelectionChange"
      >
        <template #empty>
          <el-empty :image-size="100" description="暂无数据" />
        </template>
        <el-table-column
          type="selection"
          header-align="center"
        ></el-table-column>
        <el-table-column
          label="ID"
          header-align="center"
          v-if="false"
          prop="post_id"
        />
        <el-table-column
          header-align="center"
          label="岗位名称"
          prop="post_name"
        />
        <el-table-column
          header-align="center"
          align="center"
          label="岗位编码"
          prop="post_code"
        />
        <el-table-column
          header-align="center"
          label="岗位状态"
          align="center"
          prop="post_status"
        >
          <template #default="scope">
            <el-switch
              v-model="scope.row.post_status"
              size="large"
              :inline-prompt="true"
              :active-value="1"
              :inactive-value="2"
              active-color="#13ce66"
              inactive-color="#f5222d"
              active-text="启用"
              inactive-text="停用"
              :before-change="() => handPostStatusChange(scope.row)"
              :disabled="!hasPermission('api.sysPost.state')"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          label="创建时间"
          prop="create_time"
        />
        <el-table-column header-align="center" label="描述" prop="remark" />"
        <el-table-column
          header-align="center"
          align="center"
          fixed="right"
          label="操作"
          width="190"
        >
          <template #default="scope">
            <el-button
              v-if="hasPermission('api.sysPost.show')"
              type="primary"
              class="!ml-0"
              text
              @click="handUpdatePost(scope.row)"
            >
              <template #icon>
                <i-ep-edit />
              </template>
              编辑
            </el-button>
            <el-button
              v-if="hasPermission('api.sysPost.destroy')"
              type="danger"
              class="!ml-0"
              text
              @click="handDestroyPost(scope.row)"
            >
              <template #icon><i-ep-delete /></template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <el-pagination
        class="justify-end"
        background
        @size-change="handleSizeChange()"
        @current-change="handleCurrentChange()"
        v-model:current-page="queryParams.pageNum"
        :page-sizes="[10, 20, 50, 100, 500]"
        v-model:page-size="queryParams.pageSize"
        layout="total,sizes,prev,pager,next"
        :total="tableData.total"
        prev-text="上一页"
        next-text="下一页"
        :default-page-size="10"
        :pager-count="5"
      ></el-pagination>
    </el-card>
  </div>
  <PostModel
    v-model:dialogVisible="dialogVisible"
    :post_id="post_id"
    @success="handSuccess"
  />
</template>

<script setup lang="ts">
import { reactive, onMounted, ref } from 'vue'
import { postStatusList } from './post.data'
import { PostRow } from '@/api/auth/model/postModel'
import { GetList, State, Destroy, BatchDestroy } from '@/api/auth/post'
import { FormInstance } from 'element-plus'
import { useForm } from '@/hooks'
import PostModel from './postModel.vue'
import { usePermission } from '@/hooks/permission'

const postQueryFormRef = ref<FormInstance>(null!)

const { resetForm } = useForm()
const { hasPermission } = usePermission()

const dialogVisible = ref(false)
const post_id = ref<number>(0)

//批量删除按钮是否可点击
let multiple = ref<boolean>(true)
//选中的数据
let batchIdArr = ref<number[]>([])

//搜索参数
let queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  postName: '',
  postCode: '',
  postStatus: 0,
  beginTime: '',
  endTime: '',
})

//表格及分页数据
const tableData = reactive({
  loading: true,
  total: 0,
  data: [],
})

//获取列表数据
const getPostList = async () => {
  try {
    const { code, data, message } = await GetList(queryParams)
    if (code != 200) {
      ElMessage.error(message)
      return
    }
    tableData.total = data?.total || 0
    tableData.data = (data?.rows as never[]) || []
  } finally {
    tableData.loading = false
  }
}

//搜索
const postQuerySearch = () => {
  getPostList()
}
//搜索重置
const postResetQueryForm = () => {
  resetForm(postQueryFormRef.value)
  getPostList()
}

//page-size 改变时触发
const handleSizeChange = () => {
  getPostList()
}

//current-page 改变时触发
const handleCurrentChange = () => {
  getPostList()
}

//修改状态
const handPostStatusChange = (row: PostRow) => {
  return new Promise<boolean>((resolve, reject) => {
    try {
      let text = row.post_status === 1 ? '停用' : '启用'
      ElMessageBox.confirm(`确定要${text}${row.post_name}岗位吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const { code, message } = await State({
            PostId: row.post_id,
            PostStatus: row.post_status == 1 ? 2 : 1,
          })
          if (code != 200) {
            ElMessage.error(`${text}${message}`)
            reject(false)
          }
          ElMessage.success(`${text}${message}`)
          resolve(true)
        })
        .catch(() => {
          ElMessage.info('取消修改')
          reject(false)
        })
    } catch (error) {
      reject(false)
    }
  })
}

//添加
const handCreatePost = () => {
  dialogVisible.value = true
  post_id.value = 0
}

//更新
const handUpdatePost = (row: PostRow) => {
  dialogVisible.value = true
  post_id.value = row.post_id
}

//添加/修改成功后執行
const handSuccess = () => {
  getPostList()
}

//刪除
const handDestroyPost = async (row: PostRow) => {
  ElMessageBox.confirm(`确定要删除${row.post_name}岗位吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const { code, message } = await Destroy({ PostId: row.post_id })
      if (code != 200) {
        ElMessage.error(`删除${row.post_name}${message}`)
        return
      }
      ElMessage.success(`删除${row.post_name}${message}`)
      getPostList()
    })
    .catch(() => {
      ElMessage.info('取消删除')
    })
}

//选中的数据
const handSelectionChange = (selection: PostRow[]) => {
  batchIdArr.value = selection.map((item: PostRow) => item.post_id)
  multiple.value = !selection.length
}

//批量删除
const handBacthDeletePost = () => {
  if (!batchIdArr.value.length) {
    ElMessage.warning('请选择要删除的岗位')
    return
  }
  let PostId = batchIdArr.value
  ElMessageBox.confirm(`确定要删除岗位编号为：${PostId}的数据吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const { code, message } = await BatchDestroy({ PostId: PostId })
      if (code != 200) {
        ElMessage.error(`删除${message}`)
        return
      }
      ElMessage.success(`删除${message}`)
      getPostList()
    })
    .catch(() => {
      ElMessage.info('取消删除')
    })
}

onMounted(() => {
  getPostList()
})
</script>

<style scoped></style>
